#!/bin/sh

function get_process_num() {
	return `ps aux | grep "python" | grep "mjs_startup.py" | grep -v "grep" | wc -l`
}

function kill_process() {
	pro_nums=`ps aux | grep "python" | grep "mjs_startup.py" | grep -v "grep" | wc -l`
	while [ "$pro_nums" != "0" ]; do
		pro_id=`ps aux | grep "python" | grep "mjs_startup.py" | grep -v "grep" | awk '{print $2}'`
		kill -9 $pro_id
		sleep 0.5
		pro_nums=`ps aux | grep "python" | grep "mjs_startup.py" | grep -v "grep" | wc -l`
	done
}

function start_process() {
	`cd /etc/mangjings && ./mjs_start`
}

if [ "$1" == "start" ]; then
	kill_process
	start_process
	sleep 0.5
	if [ get_process_num == "1" ]; then
		echo "mangjings start"
	else
		echo "mangjings start failed"
	fi
elif [ "$1" == "restart" ]; then
	kill_process
	start_process
	sleep 0.5
	if [ get_process_num == "1" ]; then
		echo "mangjings restart"
	else
		echo "mangjings restart failed"
	fi
elif [ "$1" == "stop" ]; then
	if [ get_process_num != "0" ]; then
		kill_process
		sleep 0.5
		if [ get_process_num != "0" ]; then
			echo "mangjings stoped"
		else
			echo "mangjings stop failed"
		fi
	fi
else
	echo "usage: mjs start [, restart][, stop]"
fi
